package com.gxa.hotel.portal.interceptor;


import com.gxa.hotel.core.exception.BusinessException;
import com.gxa.hotel.core.exception.ExceptionCode;
import com.gxa.hotel.core.util.RestUtils;
import com.gxa.hotel.portal.thread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    RestTemplate restTemplate=null;
    @Autowired
    UserThreadLocal userThreadLocal;
    static RestUtils restUtils=new RestUtils();


    /**
     * 拦截前的操作
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从前端的请求头中获取token
        String token = request.getHeader("token");
        //判断token,如果为null,直接拦死
        if (StringUtils.isEmpty(token)){

              throw new BusinessException(ExceptionCode.EMPTY_TOKEN);
        }
        String url="http://localhost:8090/user/checkWithToken";
        //发起向SSO服务器的远程调用

        MultiValueMap<String,String> parmas =new LinkedMultiValueMap<>();
        parmas.add("token",token);
        Map map = RestUtils.postWithParams(url, null, parmas);
        if (!map.get("code").equals("1")){
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        }
        userThreadLocal.set(map);
        return true;
    }
}
